namespace OFX.Aggregator.WpfApplication
{
	#region #using Directives

	using System;
	using System.Collections.Generic;
	using System.Diagnostics;
	using System.Windows.Controls;
	using System.Windows.Navigation;

	using Infrastructure;

	#endregion

	/// <summary>
	/// Interaction logic for FetchStatementProgressPage.xaml
	/// </summary>
	public partial class FetchStatementProgressPage : Page,
	                                                  IProgressReport
	{
		private readonly IIocContainerAbstraction container;
		private readonly StatementSource source;

		public FetchStatementProgressPage(StatementSource source, ProgressReportBridge progressReportBridge, IIocContainerAbstraction container)
		{
			progressReportBridge.SetPage(this);

			this.source = source;
			this.container = container;

			InitializeComponent();
		}

		#region Implementation of IProgressReport

		public StatementSource StatementSource
		{
			[DebuggerStepThrough]
			get { return this.source; }
		}

		public void OnProgress(double currentStep, double totalSteps)
		{
			this.progressBar.Value = currentStep;
			this.progressBar.Minimum = 0.0;
			this.progressBar.Maximum = totalSteps;
		}

		public void OnFinish()
		{
			NavigationService.RemoveBackEntry();

			var page = this.container.Resolve<Page>("StatementSourceListPage");
			NavigationService.Navigate(page);
			NavigationService.Navigated += NavigationService_Navigated;
		}

		public void ReportError(Exception ex)
		{
			NavigationService.RemoveBackEntry();

			var page = this.container.Resolve<Page>("ErrorReportPage", new Dictionary<string, object> {
			                                                                                          	{"exception", ex}
			                                                                                          });
			NavigationService.Navigate(page);
			NavigationService.Navigated += NavigationService_Navigated;
		}

		#endregion

		private static void NavigationService_Navigated(object sender, NavigationEventArgs e)
		{
			var navigationService = ((Page) e.Content).NavigationService;

			navigationService.Navigated -= NavigationService_Navigated;

			navigationService.RemoveBackEntry();
		}
	}
}